package com.ttloner.dao.impl;

import com.ttloner.pojo.Book;
import com.ttloner.utils.JDBCUtils;

import java.sql.Connection;
import java.util.List;

/**
 * @author TTLoner
 * @date 2021/7/9 14:55
 * @description
 */
public class BookDAOImpl extends BaseDAO implements BookDAO{
    @Override
    public int addBook(Book book) {
        Connection conn = JDBCUtils.getConnection();
        String sql="insert into t_book(`name`,`price`,`author`,`sales`,`stock`,`img_path`)" +
                "values(?,?,?,?,?,?) ";
        int updateNum = update(conn, sql, book.getName(), book.getPrice(), book.getAuthor(), book.getSales(), book.getStock(), book.getImgPath());
        JDBCUtils.close(conn);
        return updateNum;
    }

    @Override
    public int deleteBookById(Integer id) {
        Connection conn = JDBCUtils.getConnection();
        String sql="delete from t_book where `id`=?";
        int updateNum = update(conn, sql, id);
        JDBCUtils.close(conn);
        return updateNum;
    }

    @Override
    public int updateBook(Book book) {
        Connection conn = JDBCUtils.getConnection();
        String sql="update t_book set `name`=?,`price`=?,`author`=?,`sales`=?,`stock`=?,`img_path`=? where `id`=?";
        int updateNum = update(conn, sql, book.getName(), book.getPrice(), book.getAuthor(), book.getSales(), book.getStock(), book.getImgPath(),book.getId());
        JDBCUtils.close(conn);
        return updateNum;
    }

    @Override
    public Book queryBookById(Integer id) {
        Connection conn = JDBCUtils.getConnection();
        String sql="select * from t_book where `id`=?";
        Book book = queryForOne(conn, Book.class, sql, id);
        JDBCUtils.close(conn);
        return book;
    }

    @Override
    public List<Book> queryBooks() {
        Connection conn = JDBCUtils.getConnection();
        String sql="select * from t_book";
        List<Book> books = queryForList(conn, Book.class, sql);
        JDBCUtils.close(conn);
        return books;
    }
}
